﻿using System.Collections.Generic;
using System;

namespace SourceConverter.Components {
    public class ExtClassCollection : List<ExtClass> {
        
        public ExtClass FindClass(string type) {
            if (string.IsNullOrEmpty(type)) return null;

            string ns = string.Empty;
            string cls;
            if (type.Contains(".")) {
                ns = type.Substring(0, type.LastIndexOf("."));
                cls = type.Substring(type.LastIndexOf(".") + 1);
            } else {
                cls = type;
            }

            foreach (ExtClass ec in this) {
                if (ec.Name != cls) continue;

                if (!string.IsNullOrEmpty(ns)) {
                    if (ec.Namespace != ns) continue;
                }

                return ec;
            }
            return null;
        }
        
        public bool ContainsClass(ExtClass ec) {
            foreach (ExtClass cls in this) {
                if (ec.FullyQualifiedName == cls.FullyQualifiedName)  return true;
            }
            return false;
        }
        
        /// <summary>
        /// reorganizes the classes in the collection to place super classes before the subclasses
        /// </summary>
        /// <returns>the sorted collection</returns>
        public ExtClassCollection SortBySuperClass() {
            Sort(delegate(ExtClass x, ExtClass y) { return x.FullyQualifiedName.CompareTo(y.FullyQualifiedName); });
            ExtClassCollection sorted = new ExtClassCollection();
            foreach (ExtClass ec in this) {
                AddClassAndSuperClass(ec, ref sorted);
            }
            return sorted;
        }
        
        private void AddClassAndSuperClass(ExtClass ec, ref ExtClassCollection classes) {
            ExtClass super = FindClass(ec.SuperClass);
            if (super != null) AddClassAndSuperClass(super, ref classes);
            if (!classes.ContainsClass(ec)) classes.Add(ec);
        }
    }
}